﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeIT.SGI.ERP.Negocios;
using MakeIT.SGI.ERP.Entidades;
using MakeIT.Framework.Util;

namespace MakeIT.SGI.ERP.Apresentacao
{
    public partial class CadastroMvtoFin : System.Web.UI.Page
    {
        UsuarioVO usuarioVO = null;
        protected SgiDAOT SgiDAOT = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.SgiDAOT = new SgiDAOT();
            usuarioVO = (UsuarioVO)this.Session["userActive"];

            if (!IsPostBack)
            {
                cbProvisaoResgatarTickt.Checked = false;
                cbProvisaoResgatarTickt_CheckedChanged(null, null);

                cbSangriaTicketGerar.Checked = false;
                cbSangriaTicketGerar_CheckedChanged(null, null);

                atualizarDdlIdFilial(null, null);
                filtraFilialDDL(null, null);
                carregaNatureza();
                ddlCadNatureza_SelectedIndexChanged(null, null);
                Util.HabilitarCampos(false, this.panelCad);
            }

        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            try
            {
                if (this.SgiDAOT != null)
                    this.SgiDAOT.closeDAO();
            }
            catch (Exception ex) { }
        }

        protected void atualizarDdlIdFilial(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaFilial(this.SgiDAOT, this.ddlCadIdFilial);

            CarregaDDL.carregaFilial(this.SgiDAOT, this.ddlIdFilial);
        }

        protected void atualizarDdlIdBanco(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaBanco(this.SgiDAOT, this.ddlCadIdBanco, Convert.ToInt32(ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaBanco(this.SgiDAOT, this.ddlIdBanco, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void atualizarDdlIdCtaCor(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaContaCorrente(this.SgiDAOT, this.ddlCadIdCtaCor, Convert.ToInt32(ddlCadIdFilial.SelectedValue), Convert.ToInt32(ddlCadIdBanco.SelectedValue));

            CarregaDDL.carregaContaCorrente(this.SgiDAOT, this.ddlIdCtaCor, Convert.ToInt32(ddlIdFilial.SelectedValue), Convert.ToInt32(ddlIdBanco.SelectedValue));
        }

        protected void atualizarDdlIdFornecedor(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaFornecedor(this.SgiDAOT, this.ddlCadIdFornecedor, txtCadPesquisarFornecedor.Text, Convert.ToInt32(this.ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaFornecedor(this.SgiDAOT, this.ddlIdFornecedor, Convert.ToInt32(this.ddlIdFilial.SelectedValue));
        }

        protected void atualizarddlCadIdClienteRec(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaCliente(this.SgiDAOT, this.ddlCadIdClienteRec, txtCadPesquisarClienteRec.Text, Convert.ToInt32(this.ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaCliente(this.SgiDAOT, this.ddlIdClienteRec, Convert.ToInt32(this.ddlIdFilial.SelectedValue));
        }

        protected void atualizarDdlIdFormaPgto(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaFormaPagamento(this.SgiDAOT, this.ddlCadIdFormaPgto, Convert.ToInt32(ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaFormaPagamento(this.SgiDAOT, this.ddlIdFormaPgto, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void atualizarDdlIdPlnCta(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaPlanoConta(this.SgiDAOT, this.ddlCadIdPlnCta, Convert.ToInt32(ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaPlanoConta(this.SgiDAOT, this.ddlIdPlnCta, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void atualizarDdlIdCCusto(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaCentroCusto(this.SgiDAOT, this.ddlCadIdCCusto, Convert.ToInt32(ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaCentroCusto(this.SgiDAOT, this.ddlIdCCusto, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void atualizarddlIdCLucro(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaCentroLucro(this.SgiDAOT, this.ddlCadIdCLucro, Convert.ToInt32(ddlCadIdFilial.SelectedValue));

            CarregaDDL.carregaCentroLucro(this.SgiDAOT, this.ddlIdCLucroRec, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void atualizarDdlIdCaixa(object sender, ImageClickEventArgs e)
        {
            CarregaDDL.carregaCaixa(this.SgiDAOT, this.ddlIdCaixa, Convert.ToInt32(ddlIdFilial.SelectedValue));
        }

        protected void carregaNatureza()
        {
            CarregaDDL.carregaNatureza(ddlCadNatureza, false);
            CarregaDDL.carregaNatureza(ddlNatureza, true);
        }

        /// <summary>
        /// Manipula o evento do botão btnPesquisa
        /// </summary>
        /// <param name="sender">Objeto disparador do evento</param>
        /// <param name="e">Argumento do evento</param>
        protected void btnPesquisa_Click(object sender, EventArgs e)
        {

            //Declara objetos
            int? idMvtoFin = null;
            int? idFilial = null;
            int? idCtaCor = null;
            int? idFornecedor = null;
            int? idCliente = null;
            int? idFormaPgto = null;
            int? idPlnCta = null;
            int? idCLucro = null;
            int? idCCusto = null;
            int? idCaixa = null;
            int? idTitRec = null;
            int? idTitPag = null;
            char? natureza = null;
            char? tipo = null;
            int? idBanco = null;
            DateTime? dtMvtoFinDe = null;
            DateTime? dtMvtoFinAte = null;
            decimal? valorDe = null;
            decimal? valorAte = null;
            string nrDoc = null;

            try
            {

                if (!string.IsNullOrEmpty(this.txtIdMvtoFin.Text))
                {
                    idMvtoFin = Int32.Parse(this.txtIdMvtoFin.Text);
                }

                if (!ddlIdFilial.SelectedValue.Equals("-1"))
                {
                    idFilial = Int32.Parse(this.ddlIdFilial.SelectedValue);
                }

                if (!ddlIdCtaCor.SelectedValue.Equals("-1"))
                {
                    idCtaCor = Int32.Parse(this.ddlIdCtaCor.SelectedValue);
                }

                if (!ddlIdFornecedor.SelectedValue.Equals("-1"))
                {
                    idFornecedor = Int32.Parse(this.ddlIdFornecedor.SelectedValue);
                }

                if (!ddlIdClienteRec.SelectedValue.Equals("-1"))
                {
                    idCliente = Int32.Parse(this.ddlIdClienteRec.SelectedValue);
                }

                if (!ddlIdFormaPgto.SelectedValue.Equals("-1"))
                {
                    idFormaPgto = Int32.Parse(this.ddlIdFormaPgto.SelectedValue);
                }

                if (!ddlIdPlnCta.SelectedValue.Equals("-1"))
                {
                    idPlnCta = Int32.Parse(this.ddlIdPlnCta.SelectedValue);
                }

                if (!ddlIdCLucroRec.SelectedValue.Equals("-1"))
                {
                    idCLucro = Int32.Parse(this.ddlIdCLucroRec.SelectedValue);
                }

                if (!ddlIdCCusto.SelectedValue.Equals("-1"))
                {
                    idCCusto = Int32.Parse(this.ddlIdCCusto.SelectedValue);
                }

                if (!string.IsNullOrEmpty(this.txtIdTitRec.Text))
                {
                    idTitRec = Int32.Parse(this.txtIdTitRec.Text);
                }

                if (!string.IsNullOrEmpty(this.txtIdTitPag.Text))
                {
                    idTitPag = Int32.Parse(this.txtIdTitPag.Text);
                }

                if (!ddlIdCaixa.SelectedValue.Equals("-1"))
                {
                    idCaixa = Int32.Parse(this.ddlIdCaixa.SelectedValue);
                }

                if (!ddlNatureza.SelectedValue.Equals("0"))
                {
                    natureza = Convert.ToChar(ddlNatureza.SelectedValue);
                }

                if (!ddlFiltrar.SelectedValue.Equals("0"))
                {
                    tipo = Convert.ToChar(ddlFiltrar.SelectedValue);
                }

                if (!ddlIdBanco.SelectedValue.Equals("-1"))
                {
                    idBanco = Int32.Parse(this.ddlIdBanco.SelectedValue);
                }


                //-------------- data vencimento ----------------------

                if (!string.IsNullOrEmpty(this.txtdtMvtoFinDe.Text))
                {
                    dtMvtoFinDe = DateTime.Parse(this.txtdtMvtoFinDe.Text);
                }
                else if (!string.IsNullOrEmpty(this.dtMvtoFinAte.Text))
                {
                    dtMvtoFinDe = dtMvtoFinAte;
                }

                if (!string.IsNullOrEmpty(this.dtMvtoFinAte.Text))
                {
                    dtMvtoFinAte = DateTime.Parse(this.dtMvtoFinAte.Text);
                }
                else if (!string.IsNullOrEmpty(this.txtdtMvtoFinDe.Text))
                {
                    dtMvtoFinAte = dtMvtoFinDe;
                }


                //-------------- valor ----------------------

                if (!string.IsNullOrEmpty(this.txtValorDe.Text))
                {
                    valorDe = Decimal.Parse(this.txtValorDe.Text);
                }
                else if (!string.IsNullOrEmpty(this.txtValorAte.Text))
                {
                    valorDe = valorAte;
                }

                if (!string.IsNullOrEmpty(this.txtValorAte.Text))
                {
                    valorAte = Decimal.Parse(this.txtValorAte.Text);
                }
                else if (!string.IsNullOrEmpty(this.txtValorDe.Text))
                {
                    valorAte = valorDe;
                }

                if (!String.IsNullOrEmpty(txtNrDoc.Text))
                {
                    nrDoc = txtNrDoc.Text;
                }


                //Recupera a lista de registros segundo a pesquisa
                this.grvResultado.DataSource = SgiDAOT.getMvtofins(idMvtoFin, idFilial, idCtaCor, idFornecedor, idCliente, idFormaPgto, idPlnCta, idCLucro, idCCusto, idCaixa, idTitRec, idTitPag, natureza, tipo, idBanco, dtMvtoFinDe, dtMvtoFinAte, valorDe, valorAte, nrDoc);

                //Vincula os dados
                this.grvResultado.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }   

        protected void imgbVisualizar_Click(object sender, ImageClickEventArgs e)
        {
            // Declara objetos
            MvtofinVO mvtofinVO = null;
            int idMvtofinVO = 0;

            try
            {
                //Recupera os argumentos com o ID do objeto
                string[] argumentos = ((ImageButton)sender).CommandArgument.Split(';');
                idMvtofinVO = Int32.Parse(argumentos[0]);

                //Limpa formulario, para a entrada de novo registro
                Util.LimparCampos(this.panelCad);

                //Recupera o objeto
                mvtofinVO = SgiDAOT.getMvtofin(idMvtofinVO);

                this.txtCadIdMvtoFin.Text = mvtofinVO.idMvtoFin.ToString();
                this.ddlCadIdFilial.SelectedValue = Convert.ToString(mvtofinVO.idFilial);
                if (mvtofinVO.idCtaCor != null)
                {
                    mvtofinVO.idCtaCorVO = this.SgiDAOT.getCtacor(mvtofinVO.idCtaCor);
                    this.ddlCadIdBanco.SelectedValue = Convert.ToString(mvtofinVO.idCtaCorVO.idBanco);
                    ddlBanco_SelectedIndexChanged(null, null);
                    this.ddlCadIdCtaCor.SelectedValue = Convert.ToString(mvtofinVO.idCtaCor);
                }
                if(mvtofinVO.idFormaPgto != null)
                    this.ddlCadIdFormaPgto.SelectedValue = Convert.ToString(mvtofinVO.idFormaPgto);
                if (mvtofinVO.idFormaPgto != null)
                    this.ddlCadIdFormaPgto.SelectedValue = Convert.ToString(mvtofinVO.idFormaPgto);
                if(mvtofinVO.idPlnCta != null)
                    this.ddlCadIdPlnCta.SelectedValue = Convert.ToString(mvtofinVO.idPlnCta);
                if (mvtofinVO.natureza == 'C')
                {
                    this.ddlCadNatureza.SelectedValue = "C";
                    this.ddlCadNatureza_SelectedIndexChanged(null, null);
                    if (mvtofinVO.idCliente != null)
                    {
                        mvtofinVO.idClienteVO = this.SgiDAOT.getCliente(mvtofinVO.idCliente);
                        this.txtCadPesquisarClienteRec.Text = mvtofinVO.idClienteVO.pessoa;
                        atualizarddlCadIdClienteRec(null, null);
                        this.ddlCadIdClienteRec.SelectedValue = Convert.ToString(mvtofinVO.idCliente);
                    }
                    if(mvtofinVO.idCLucro != null)
                        this.ddlCadIdCLucro.SelectedValue = Convert.ToString(mvtofinVO.idCLucro);
                }
                else
                {
                    this.ddlCadNatureza.SelectedValue = "D";
                    this.ddlCadNatureza_SelectedIndexChanged(null, null);
                    if (mvtofinVO.idFornecedor != null)
                    {
                        mvtofinVO.idFornecedorVO = this.SgiDAOT.getFornecedor(mvtofinVO.idFornecedor);
                        this.txtCadPesquisarFornecedor.Text = mvtofinVO.idFornecedorVO.pessoa;
                        atualizarDdlIdFornecedor(null, null);
                        this.ddlCadIdFornecedor.SelectedValue = Convert.ToString(mvtofinVO.idFornecedor);
                    }
                    if(mvtofinVO.idCCusto != null)
                        this.ddlCadIdCCusto.SelectedValue = Convert.ToString(mvtofinVO.idCCusto);
                }
                if (!String.IsNullOrEmpty(mvtofinVO.nrDoc))
                    this.txtCadNrDoc.Text = mvtofinVO.nrDoc;

                this.txtCadVcto.Text = mvtofinVO.dtMvtoFin.ToShortDateString();
                this.txtCadValor.Text = Convert.ToString(mvtofinVO.valor);
                this.txtCadValorJuroC.Text = Convert.ToString(mvtofinVO.valorJuro);
                this.txtCadValorDescC.Text = Convert.ToString(mvtofinVO.valorDesc);
                this.txtCadValorPago.Text = Convert.ToString(mvtofinVO.valorPago);

                decimal resultado = (decimal)((mvtofinVO.valor + mvtofinVO.valorJuro) - (mvtofinVO.valorPago + mvtofinVO.valorDesc));

                if (resultado >= 0)
                    txtCadValorSaldo.Text = Convert.ToString(resultado);

                this.ltCadastradoPor.Text = mvtofinVO.cadastradoPor;
                this.ltEditadoPor.Text = mvtofinVO.editadoPor;
                this.ltDataCadastro.Text = mvtofinVO.cadastro.ToString("dd/MM/yyyy");
                this.ltDataEdicao.Text = mvtofinVO.edicao.ToString("dd/MM/yyyy");

                //Habilita tab page do cadastro
                this.tabMvtoFin.ActiveTabIndex = 1;

                //Desabilita campos para edição
                Util.HabilitarCampos(false, this.panelCad);

                ////Habilita botão novo
                this.btnNovo.Enabled = true;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            //Declara objetos
            MvtofinVO mvtofinVO = null;
            bool novoRegistro = false;

            try
            {
                //Verifica se o ID é nulo, se sim = cadastro novo
                if (string.IsNullOrEmpty(this.txtCadIdMvtoFin.Text))
                {
                    mvtofinVO = MvtofinVO.CreateVO();
                    mvtofinVO.cadastro = DateTime.Now;
                    mvtofinVO.cadastradoPor = usuarioVO.user;

                    novoRegistro = true;
                }
                //Recupera dados para serem alterados
                else
                {
                    //Recupera dados
                    mvtofinVO = this.SgiDAOT.getMvtofin(Int32.Parse(this.txtCadIdMvtoFin.Text));
                }

                mvtofinVO.idFilial = Int32.Parse(this.ddlCadIdFilial.SelectedValue);
                if (this.ddlCadIdCtaCor.SelectedValue.Equals("-1"))
                    mvtofinVO.idCtaCor = null;
                else
                    mvtofinVO.idCtaCor = Int32.Parse(this.ddlCadIdCtaCor.SelectedValue);


                mvtofinVO.natureza = Convert.ToChar(this.ddlCadNatureza.SelectedValue);

                if(mvtofinVO.natureza == 'D')
                {
                    if (this.ddlCadIdFornecedor.SelectedValue.Equals("-1"))
                        mvtofinVO.idFornecedor = null;
                    else
                        mvtofinVO.idFornecedor = Int32.Parse(this.ddlCadIdFornecedor.SelectedValue);

                    if (this.ddlCadIdCCusto.SelectedValue.Equals("-1"))
                        mvtofinVO.idCCusto = null;
                    else
                        mvtofinVO.idCCusto = Int32.Parse(this.ddlCadIdCCusto.SelectedValue);  
                }
                else
                {
                    if (this.ddlCadIdClienteRec.SelectedValue.Equals("-1"))
                        mvtofinVO.idCliente = null;
                    else
                        mvtofinVO.idCliente = Int32.Parse(this.ddlCadIdClienteRec.SelectedValue);

                    if (this.ddlCadIdCLucro.SelectedValue.Equals("-1"))
                        mvtofinVO.idCLucro = null;
                    else
                        mvtofinVO.idCLucro = Int32.Parse(this.ddlCadIdCLucro.SelectedValue);  
                }

                if (this.ddlCadIdFormaPgto.SelectedValue.Equals("-1"))
                    mvtofinVO.idFormaPgto = null;
                else
                    mvtofinVO.idFormaPgto = Int32.Parse(this.ddlCadIdFormaPgto.SelectedValue);
                if (this.ddlCadIdPlnCta.SelectedValue.Equals("-1"))
                    mvtofinVO.idPlnCta = null;
                else
                    mvtofinVO.idPlnCta = Int32.Parse(this.ddlCadIdPlnCta.SelectedValue);

                if (string.IsNullOrEmpty(this.txtCadNrDoc.Text))
                    mvtofinVO.nrDoc = null;
                else
                    mvtofinVO.nrDoc = this.txtCadNrDoc.Text;
                mvtofinVO.dtMvtoFin = DateTime.Parse(this.txtCadVcto.Text);

                if (!cbProvisaoResgatarTickt.Checked)
                {

                    mvtofinVO.valor = decimal.Parse(this.txtCadValor.Text.Replace(".", ""));
                    mvtofinVO.valorJuro = decimal.Parse(this.txtCadValorJuroC.Text.Replace(".", ""));
                    mvtofinVO.valorDesc = decimal.Parse(this.txtCadValorDescC.Text.Replace(".", ""));
                    mvtofinVO.valorPago = decimal.Parse(this.txtCadValorPago.Text.Replace(".", ""));

                    decimal resultado = (decimal)((mvtofinVO.valor + mvtofinVO.valorJuro) - (mvtofinVO.valorPago + mvtofinVO.valorDesc));

                    if (resultado >= 0)
                    {
                        mvtofinVO.valorDesc += resultado;
                        txtCadValorDescC.Text = Convert.ToString(mvtofinVO.valorDesc);
                        txtCadValorSaldo.Text = Convert.ToString(resultado);
                    }
                    else
                    {
                        Util.ExibeAlert(this, "O valor do saldo não pode ser menor que zero! Altere o valor do título!");
                        return;
                    }

                }
                else
                {
                    mvtofinVO.valorJuro = 0;
                    mvtofinVO.valorDesc = 0;
                    mvtofinVO.valorPago = 0;
                }

                mvtofinVO.edicao = DateTime.Now;
                mvtofinVO.editadoPor = usuarioVO.user;

                this.SgiDAOT.transactionBegin();

                //Chama metodo para salvar ou criar novo registro
                if (novoRegistro)
                {
                    mvtofinVO.idMvtoFin = (int)this.SgiDAOT.newMvtofin(mvtofinVO);
                    if (cbProvisaoResgatarTickt.Checked)
                    {
                        TicketfinVO ticketfinVO = this.SgiDAOT.getTicketfin(Convert.ToInt32(ddlProvisaoTicket.SelectedValue));
                        ticketfinVO.idMvtoFinA = mvtofinVO.idMvtoFin;
                        ticketfinVO.situacao = 'A';
                        ticketfinVO.dtAcolhimento = DateTime.Now;
                        mvtofinVO.nrDoc = "Ticket: " + ticketfinVO.idTicketFin;
                        mvtofinVO.valor = ticketfinVO.valor;
                        ticketfinVO.editadoPor = usuarioVO.user;
                        ticketfinVO.edicao = DateTime.Now;

                        this.SgiDAOT.setTicketfin(ticketfinVO);
                        this.SgiDAOT.setMvtofin(mvtofinVO);
                    }
                    else if (cbSangriaTicketGerar.Checked)
                    {
                        TicketfinVO ticketfinVO = TicketfinVO.CreateVO();
                        ticketfinVO.idFilial = mvtofinVO.idFilial;
                        ticketfinVO.idMvtoFin = mvtofinVO.idMvtoFin;
                        ticketfinVO.situacao = 'T';
                        ticketfinVO.finalidade = txtSangriaTicketFinalidade.Text;
                        ticketfinVO.origem = "FINANCEIRO";
                        ticketfinVO.dtTicketFin = DateTime.Now;
                        ticketfinVO.valor = mvtofinVO.valor;
                        ticketfinVO.cadastradoPor = usuarioVO.user;
                        ticketfinVO.cadastro = DateTime.Now;
                        ticketfinVO.editadoPor = usuarioVO.user;
                        ticketfinVO.edicao = DateTime.Now;

                        this.SgiDAOT.newTicketfin(ticketfinVO);
                    }


                }
                else
                {
                    this.SgiDAOT.setMvtofin(mvtofinVO);
                }

                txtCadIdMvtoFin.Text = Convert.ToString(mvtofinVO.idMvtoFin);
                txtCadNrDoc.Text = mvtofinVO.nrDoc;
                txtCadValor.Text = Convert.ToString(mvtofinVO.valor);

                decimal resultadoF = (decimal)((mvtofinVO.valor + mvtofinVO.valorJuro) - (mvtofinVO.valorPago + mvtofinVO.valorDesc));
                txtCadValorSaldo.Text = Convert.ToString(resultadoF);


                // Exibe msg de sucesso ao salvar registro
                Util.ExibeAlert(this, "Registro salvo com sucesso!");

                //Popula grid atualizado
                this.btnPesquisa_Click(null, null);
                this.btnCancelar_Click(null, null);

                //Atualiza formulario, apos salvar os dados
                this.ltCadastradoPor.Text = mvtofinVO.cadastradoPor;
                this.ltEditadoPor.Text = mvtofinVO.editadoPor;
                this.ltDataCadastro.Text = mvtofinVO.cadastro.ToString("dd/MM/yyyy");
                this.ltDataEdicao.Text = mvtofinVO.edicao.ToString("dd/MM/yyyy");

                cbProvisaoResgatarTickt.Checked = false;
                cbProvisaoResgatarTickt_CheckedChanged(null, null);
                cbSangriaTicketGerar.Checked = false;
                cbSangriaTicketGerar_CheckedChanged(null, null);

                this.SgiDAOT.transactionCommit();
            }
            catch (Exception ex)
            {
                if (this.SgiDAOT != null)
                    this.SgiDAOT.transactionRollBack();
                Util.ExibeAlert(this, "Registro NÃO salvo! Erro: " + ex.Message);
            }
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            //Volta para a tab page de pesquisa
            //this.tabTitpag.ActiveTabIndex = 0;

            // Desabilita os campos para edição
            Util.HabilitarCampos(false, this.panelCad);

            btnPesquisarFornecedor.Enabled = false;

            // Detrava botão de novo
            this.btnNovo.Enabled = true;

            // Desabilita o botão salvar
            this.btnSalvar.Enabled = false;
        }

        protected void btnEditar_Click(object sender, EventArgs e)
        {

        }

        protected void btnNovo_Click(object sender, EventArgs e)
        {
            //Limpa formulario, para a entrada de novo registro
            Util.LimparCampos(this.panelCad);
            // Habilita os campos para edição
            Util.HabilitarCampos(true, this.panelCad);

            this.ddlCadIdBanco.SelectedValue = "-1";
            ddlBanco_SelectedIndexChanged(null, null);

            this.ddlCadNatureza.SelectedValue = "C";
            ddlCadNatureza_SelectedIndexChanged(null, null);

            this.txtCadValorJuroC.Text = "0,00";
            this.txtCadValorDescC.Text = "0,00";
            this.txtCadValorPago.Text = "0,00";
            this.txtCadValorSaldo.Text = "0,00";

            this.ltCadastradoPor.Text = "";
            this.ltEditadoPor.Text = "";
            this.ltDataCadastro.Text = "";
            this.ltDataEdicao.Text = "";

            cbProvisaoResgatarTickt.Checked = false;
            cbProvisaoResgatarTickt_CheckedChanged(null, null);

            cbSangriaTicketGerar.Checked = false;
            cbSangriaTicketGerar_CheckedChanged(null, null);

            // Trava apenas os text box da PK
            this.txtCadIdMvtoFin.Enabled = false;

            btnPesquisarFornecedor.Enabled = true;
            btnPesquisarClienteRec.Enabled = true;

            // Trava botão de novo
            this.btnNovo.Enabled = false;

            // Habilita o botão salvar
            this.btnSalvar.Enabled = true;
        }

        protected void btnExcluir_Click(object sender, EventArgs e)
        {

        }

        protected void filtraFilialDDL(object sender, EventArgs e)
        {
            atualizarDdlIdBanco(null, null);
            atualizarDdlIdCtaCor(null, null);
            atualizarDdlIdFornecedor(null, null);
            atualizarddlCadIdClienteRec(null, null);
            atualizarDdlIdFormaPgto(null, null);
            atualizarDdlIdPlnCta(null, null);
            atualizarDdlIdCCusto(null, null);
            atualizarddlIdCLucro(null, null);
            atualizarDdlIdCaixa(null, null);
        }

        protected void ddlBanco_SelectedIndexChanged(object sender, EventArgs e)
        {
            atualizarDdlIdCtaCor(null, null);
        }

        protected void ddlCadNatureza_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool credito;
            if (ddlCadNatureza.SelectedValue == "C")
                credito = true;
            else
                credito = false;

            pnlResTicket.Enabled = credito;
            pnlResTicket.Visible = credito;
            pnlCadCliente.Enabled = credito;
            pnlCadCliente.Visible = credito;
            pnlCadCLucro.Enabled = credito;
            pnlCadCLucro.Visible = credito;

            pnlGerTicket.Enabled = !credito;
            pnlGerTicket.Visible = !credito;
            pnlCadFornecedor.Enabled = !credito;
            pnlCadFornecedor.Visible = !credito;
            pnlCadCCusto.Enabled = !credito;
            pnlCadCCusto.Visible = !credito;

            cbProvisaoResgatarTickt.Checked = false;
            cbProvisaoResgatarTickt_CheckedChanged(null, null);
            cbSangriaTicketGerar.Checked = false;
            cbSangriaTicketGerar_CheckedChanged(null, null);
        }

        protected void btnPesquisarFornecedor_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtCadPesquisarFornecedor.Text) && !ddlCadIdFilial.SelectedValue.Equals("-1"))
                atualizarDdlIdFornecedor(null, null);
            else
                Util.ExibeAlert(this, "Informe a pessoa e a filial para a pesquisa!");
        }

        protected void btnPesquisarClienteRec_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtCadPesquisarClienteRec.Text) && !ddlCadIdFilial.SelectedValue.Equals("-1"))
                atualizarddlCadIdClienteRec(null, null);
            else
                Util.ExibeAlert(this, "Informe a pessoa e a filial para a pesquisa!");
        }

        protected void grvResultado_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                MvtofinVO mvtofinVO = (MvtofinVO)e.Row.DataItem;

                ImageButton imgbVisualizar = (ImageButton)e.Row.FindControl("imgbVisualizar");
                Image imgVisualizarCaixa = (Image)e.Row.FindControl("imgVisualizarCaixa");
                HyperLink hlbVisualizarTitRec = (HyperLink)e.Row.FindControl("hlbVisualizarTitRec");
                HyperLink hlbVisualizarTitPag = (HyperLink)e.Row.FindControl("hlbVisualizarTitPag");


                
                if (mvtofinVO.idTitRec != null)
                {
                    imgbVisualizar.Visible = false;
                    imgVisualizarCaixa.Visible = false;
                    hlbVisualizarTitRec.Visible = true;
                    hlbVisualizarTitPag.Visible = false;
                }
                else if (mvtofinVO.idTitPag != null)
                {
                    imgbVisualizar.Visible = false;
                    imgVisualizarCaixa.Visible = false;
                    hlbVisualizarTitRec.Visible = false;
                    hlbVisualizarTitPag.Visible = true;
                }
                else if (mvtofinVO.idCaixa != null)
                {
                    imgbVisualizar.Visible = false;
                    imgVisualizarCaixa.Visible = true;
                    hlbVisualizarTitRec.Visible = false;
                    hlbVisualizarTitPag.Visible = false;
                }
                else
                {
                    imgbVisualizar.Visible = true;
                    imgVisualizarCaixa.Visible = false;
                    hlbVisualizarTitRec.Visible = false;
                    hlbVisualizarTitPag.Visible = false;
                }
            }
        }

        protected void cbProvisaoResgatarTickt_CheckedChanged(object sender, EventArgs e)
        {
            List<TicketfinVO> tfVOLista = new List<TicketfinVO>();

            bool exibirValores = true;

            lblProvisaoErro.Text = String.Empty;

            if (cbProvisaoResgatarTickt.Checked)
            {
                tfVOLista.AddRange(this.SgiDAOT.getTicketfins(null, null, usuarioVO.idPessoaVO.idFilial, null, null, null, 'T'));

                if (tfVOLista.Count > 0)
                {

                    ddlProvisaoTicket.Enabled = true;
                    ddlProvisaoTicket.DataValueField = "PKString";
                    ddlProvisaoTicket.DataTextField = "toString";
                    ddlProvisaoTicket.DataSource = tfVOLista;
                    ddlProvisaoTicket.DataBind();

                    exibirValores = false;
                }
                else
                {
                    ddlProvisaoTicket.Enabled = false;
                    CarregaDDL.carregaNULL(ddlProvisaoTicket);

                    cbProvisaoResgatarTickt.Checked = false;

                    lblProvisaoErro.Text = "Nenhum Ticket Encontrado!";
                    
                    exibirValores = true;
                }
            }
            else
            {
                ddlProvisaoTicket.Enabled = false;
                CarregaDDL.carregaNULL(ddlProvisaoTicket);

                cbProvisaoResgatarTickt.Checked = false;

                exibirValores = true;
            }

            pnlValores.Enabled = exibirValores;
            pnlValores.Visible = exibirValores;


        }

        protected void cbSangriaTicketGerar_CheckedChanged(object sender, EventArgs e)
        {
            bool sangria = false;

            if(cbSangriaTicketGerar.Checked)
                sangria = true;


             rfvtxtSangriaTicketFinalidade.Enabled = sangria;
             txtSangriaTicketFinalidade.Enabled = sangria;
             txtSangriaTicketFinalidade.Text = String.Empty;

        }

    }
}